<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(item, index) in list"
      :key="index"
      :title="item"
      icon="search"
      @click="$emit('search', item)"
    >
      <template #title>
        <span v-html="hightColorText(item)"></span>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestionApi } from "@/api/search";
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [],
    };
  },
  computed: {},
  watch: {
    searchText: {
      //   handler() {
      //     // if (this.timer) {
      //     //   clearInterval(this.timer);
      //     // }
      //     // this.timer = setTimeout(() => {
      //     //   this.initData();
      //     // }, 2000);
      //   },
      handler: debounce(function () {
        this.initData();
      }, 3000),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async initData() {
      try {
        let { data } = await getSearchSuggestionApi({ q: this.searchText });
        console.log(data);
        if (data.data.options.length === 1 && data.data.options[0] === null) {
          this.list = [];
        } else {
          this.list = data.data.options;
        }
      } catch (error) {
        console.log(error);
      }
    },
    hightColorText(text) {
      let reg = new RegExp(this.searchText, "gi");
      return text.replace(
        reg,
        `<span style='color:red'> ${this.searchText}</span>`
      );
    },
  },
};
</script>

<style scoped lang="less"></style>
